package com.wqr.it.ecwdr.service;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.wqr.it.ecwdr.dao.IProductItemDao;
import com.wqr.it.ecwdr.dto.ProductDto;
import com.wqr.it.ecwdr.util.DateUtils;
import com.wqr.it.ecwdr.vo.PageVO;
import com.wqr.it.ecwdr.vo.ProductItemVO;


@Async
@Service
//@CacheConfig(cacheNames = "product")
@Transactional
public class ProductService {
	private static final Logger log = LoggerFactory.getLogger("INFO");
	@Value("${ecwdr.product.productQueueSize}")
	private int productQueueSize = 1000;
	
	private ArrayBlockingQueue<ProductDto> productQueue = new ArrayBlockingQueue<>(productQueueSize);

	@Autowired  
    private OptionService optionService;

	@Autowired  
    private IProductItemDao productItemDao;
	
	private PageVO pageVO = new PageVO();
	
	private Random ran = new Random();
	
	//@Cacheable(key="product.item.token")
	public int findProductItemToken() {
		return optionService.generateToken("productItem.token", false);
	}
	
	//@CachePut(key="product.item.token")
	public int updateProductItemToken() {
		return optionService.generateToken("productItem.token", true);
	}
	
	//@Cacheable(key="product.item.follow.token")
	public int findProductItemFollowToken() {
		return optionService.generateToken("productItem.follow.token", false);
	}
	//@CachePut(key="product.item.follow.token")
	public int updateProductItemFollowToken() {
		return optionService.generateToken("productItem.follow.token", true);
	}
	
	public ProductService() {
		pageVO.setPageSize(productQueueSize / 2);
		pageVO.setCurPage(ran.nextInt(25) + 1);
	}
	
	@Scheduled(fixedRate=600000) 
	public void schedule() {
		System.out.println(DateUtils.currentDate() + " ProductService updateFavSallerProduct...");
		productItemDao.updateFavSallerProduct();
	}

	public long getProductId(ProductItemVO productItemVO) {
		return productItemDao.getProductId(productItemVO);		
	}

	public void updateProduct(ProductItemVO productItemVO) {
		if (productItemVO != null) {
			if (productItemVO.getId() > 0) {
				productItemDao.updateProduct(productItemVO);
			} else {
				productItemDao.insertProduct(productItemVO);
				long productId = productItemDao.getProductId(productItemVO);
				productItemVO.setId(productId);
			}
		}
	}

}
